import Router from 'koa-router'
import Redis from 'koa-redis'
import nodeMailer from 'nodemailer'
import email from '../config.js'
import passport from '../tools/passport.js'
import User from '../model/user.js'
import axios from '../tools/axios.js'

let router = new Router({prefix: '/user'})
let Store = new Redis().client

/**
 * @dateTime:2018/01/07
 * @author:yang
 * @desc:注册用户
 */
router.post('/signup' , async (ctx) => {
    let {username , password , email , code , uid} = ctx.request.body;
    if(code){
        let nowTime = new Date().getTime();
        let saveCode = await Store.hget(`user${username}` , 'code');
        let stmp = await Store.hget(`user${username}` , 'expire');
        if(code != saveCode){
            ctx.body = {
                code: -1,
                msg: '请输入正确的验证码'
            }
            return false
        }else{
            if(nowTime - stmp > 0){
                ctx.body = {
                    code: -1,
                    msg: '请求超时，请重新获取验证码'
                }
                return false
            }
        }
    }
    let result = await User.find({username});
    if(result.length){
        ctx.body = {
            code: -1,
            msg: '用户名已存在'
        }
        return false
    }
    let newUser = await User.create({username , password , email});
    if(newUser){
        ctx.body = {
            code: 0,
            msg: '注册成功'
        }
    }else{
        ctx.body = {
            code: -1,
            msg: '注册失败'
        }
    }
})

/**
 * @dateTime:2018/01/07
 * @author:yang
 * @desc:用户退出
 */
router.get('/exit' , async(ctx) => {
    ctx.logout();
    ctx.body = {
        code: 0,
        msg: '退出成功'
    }
})

/**
 * @dateTime:2018/01/07
 * @author:yang
 * @desc:用户登录
 */
router.post('/login' , async(ctx , next) => {
    return passport.authenticate('local' , (err, user, info, status) => {
        if(err){
            ctx.body = {
                code: -1,
                msg: err
            }
        }else{
            if(user){
                ctx.body = {
                    code: 0,
                    msg: '登录成功'
                }
                return ctx.login(user)
            }else{
                ctx.body = {
                    code: -1,
                    msg: info.message === 'Missing credentials' ? '用户名和密码都不能为空' : info.message
                }    
            }
        }
    })(ctx , next)
})

/**
 * @dateTime:2018/01/08
 * @author:yang
 * @desc:通过邮箱获取验证码
 */
router.post('/checkCode' , async(ctx) => {
    let nowTime = new Date().getTime();
    let stmp = await Store.hget(`user${ctx.request.body.username}` , 'expire');
    if(stmp && nowTime - stmp < 0){
        ctx.body = {
            code: -1,
            msg: '您的请求次数过于频繁，1分钟1次'
        }
        return false
    } 
    let mailTransport = nodeMailer.createTransport({
        host: email.smtp.host,
        secureConnection: true,
        auth:{
            user: email.smtp.user,
            pass: email.smtp.pass    
        }
    })

    let source = {
        uid: ctx.request.body.uid,
        username: ctx.request.body.username,
        email: ctx.request.body.email,
        code: email.smtp.code(),
        expire: email.smtp.expire()
    }

    let mailOptions = {
        from: `"认证邮件"${email.smtp.user}`,
        to: source.email,
        subject: '《美团网》注册码',
        html: `您在《美团网》中注册成功，您的注册码是${source.code}`
    }

    await mailTransport.sendMail(mailOptions , (err , info) => {
        if(err){
            ctx.body = {
                code: -1,
                msg: err
            }
        }else{
            Store.hmset(`user${source.username}` , 'email' , source.email , 'code' , source.code , 'expire' , source.expire);  
        }
    })
    ctx.body = {
        code: 0,
        msg: '验证码发送成功，有效期1分钟'
    }
})

/**
 * @dateTime:2018/01/08
 * @author:yang
 * @desc:获取用户名
 */
router.get('/getUser' , async(ctx) => {
    if(ctx.isAuthenticated()){
        ctx.body = {
            code: 0,
            username: ctx.session.passport.user.username
        }
    }else{
        ctx.body = {
            code: -1,
            username: ''
        }
    }
})

export default router